/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BankClientPrototype;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.Vector;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author sjt5097
 */
public class ClientHandler extends Thread {

    PrintWriter pw;
    BufferedReader bf;
    String productIdentity;
    public static int accountStore;
    public  String FirstName;
    public  String accountType;
    public  double amount;

    public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();

        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                vector.add(rs.getObject(columnIndex));
            }
            data.add(vector);
        }
        return new DefaultTableModel(data, columnNames);
    }

    public static void main(String[] args) throws InterruptedException {
        ClientLogin cl = new ClientLogin();
        cl.setVisible(true);
    }

    protected void fromLogin(ClientLogin cl, String username, char[] password, ClientHomepage ch) {
        EncryptUtils encrypt = new EncryptUtils();
        String temp = new String(password);
        String xor = encrypt.xorMessage(temp, "VedishShahSeanTeevanRyanDwyer");
        String pass = encrypt.base64encode(xor);
        System.out.println("Encryption is: " + pass);

        try {
            Socket s = new Socket("localhost", 1024);
            pw = new PrintWriter(s.getOutputStream(), true);
            bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

            pw.println("L" + username + " " + pass);
            String serverResponse = bf.readLine();
            System.out.println("Server said: " + serverResponse);
            String[] arr = serverResponse.split("\\s+");
            System.out.println(arr.length);
            // arr is: response(0), accountStore(1), FirstName(2), AccountType(3), Amount(4)
            
            String response = arr[0];
            accountStore = Integer.parseInt(arr[1]);
            setFName(arr[2]);
            setAType(arr[3]);
            setAmount(Double.parseDouble(arr[4]));
            
            System.out.println("AccountStore value is: " + accountStore +
                               "\nFirstname is: " + getFName() +
                               "\nAccountType is: " + getAType() +
                               "\nAmount is: " + getAmount());

            if(response.equals("LoggedIn"))
            {
                ch = new ClientHomepage();
                ch.setVisible(true);
                cl.setVisible(false);
                cl.dispose();
            }
            else
            {
                System.out.println("Not Logged In");
            }
//            if (serverResponse.equals("Accept User")) {
//                try {
//                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//                    Connection con = DriverManager.getConnection("jdbc:odbc:Client");
//                    Statement stmt = con.createStatement();
//                    ResultSet rs = stmt.executeQuery("SELECT * FROM OnlineInfo WHERE UserName = '" + username + "' AND Password = '" + pass + "'");
//                    while (rs.next()) {
//                        accountStore = rs.getInt("AccountNumber");
//                        ResultSet rs1 = stmt.executeQuery("SELECT FirstName FROM UserInfo WHERE SavingsAccount = " + accountStore + " OR CheckingAccount = " + accountStore + "");
//                        while (rs1.next()) {
//                            String fName = rs1.getString("FirstName");
//                            setFName(fName);
//                            ResultSet rs2 = stmt.executeQuery("SELECT AccountType, Amount FROM Accounts WHERE AccountNumber = " + accountStore + "");
//                            while (rs2.next()) {
//                                double amountIn = rs2.getDouble("Amount");
//                                setAmount(amountIn);
//                                String aType = rs2.getString("AccountType");
//                                setAType(aType);
//                                con.close();
//                                ch = new ClientHomepage();
//                                ch.setVisible(true);
//                                cl.setVisible(false);
//                                cl.dispose();
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                }
//            }
            pw.close();
            bf.close();
            s.close();
        } catch (Exception ex) {
            System.out.println("Problem establishing a connection.");
        }
    }

    protected void TransDisplay() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:Client");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM Transactions WHERE AccountFrom = " + accountStore + " OR AccountTo = " + accountStore + "");
            JTable table = new JTable(ClientHandler.buildTableModel(rs));
            JOptionPane.showMessageDialog(null, new JScrollPane(table));
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void toLoginFromHome(ClientHomepage ch) {
        ClientLogin cl = new ClientLogin();
        cl.setVisible(true);
        ch.setVisible(false);
        ch.dispose();
    }

    protected void fromTransfer(ClientTransfer ct) {
        ClientHomepage ch = new ClientHomepage();
        ch.setVisible(true);
        ct.setVisible(false);
        ct.dispose();
    }

    protected void toTransfer(ClientHomepage cHome) {
        ClientTransfer ct = new ClientTransfer();
        ct.setVisible(true);
        cHome.setVisible(false);
    }

    public String getFName() {
        return this.FirstName;
    }

    public void setFName(String FName) {
        this.FirstName = FName;
    }

    public double getAmount() {
        return this.amount;
    }

    public void setAmount(double amt) {
        this.amount = amt;
    }

    public String getAType() {
        return this.accountType;
    }

    public void setAType(String AType) {
        if (AType.equals("S")) {
            this.accountType = "Savings";
        } else {
            this.accountType = "Checking";
        }
    }

    protected void fromRegister(ClientRegister cr) {
        ClientLogin frame = new ClientLogin();
        frame.setVisible(true);
        cr.setVisible(false);
    }

    protected boolean registering(String userName, char[] password, int savings, int checking) {
        EncryptUtils encrypt = new EncryptUtils();
        String temp = new String(password);
        String xor = encrypt.xorMessage(temp, "VedishShahSeanTeevanRyanDwyer");
        String pass = encrypt.base64encode(xor);
        System.out.println("Register Encryption is: " + pass);
        try {
            Socket s = new Socket("localhost", 1024);
            pw = new PrintWriter(s.getOutputStream(), true);
            bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

            pw.println("R");
            String sResponse = bf.readLine();
            if (sResponse.equals("Register"));
            {
                System.out.println("r0");
                if (savings != 0) {
                    try {
                        System.out.println("r1");
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        System.out.println("r2");
                        Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                        System.out.println("r3");
                        Statement stmt = con.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT * FROM Accounts WHERE AccountNumber = " + savings + "");
                        System.out.println("r4");
                        while (rs.next()) {
                        System.out.println("r5");
                            stmt.executeUpdate("INSERT INTO OnlineInfo (UserName, Password, AccountNumber) VALUES ('" + userName + "', '" + pass + "', " + savings + ")");
                            System.out.println("Inserted");
                            System.out.println("r6");
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                } else if (checking != 0) {
                    try {
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                        Statement stmt = con.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT * FROM Accounts WHERE AccountNumber = " + checking + "");
                        while (rs.next()) {
                            stmt.executeUpdate("INSERT INTO OnlineInfo (UserName, Password, AccountNumber) VALUES ('" + userName + "', '" + pass + "', " + checking + ")");
                            con.close();
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /*
     * doTransfer() is a method that connects to the database
     * It takes the originating account (accountFrom) and the
     * destination account (accountTo), as well as the amount
     * to be transfered.  This method extracts the data to be
     * edited, modifies them, and injects them back into the
     * database in the proper places.
     */
    protected void doTransfer(int accountFrom, int accountTo, double amount) {
        if (accountFrom == accountStore) {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                Statement stmt = con.createStatement();
                //Amount is taken from originating account first
                ResultSet rs1 = stmt.executeQuery("SELECT Amount FROM Accounts WHERE AccountNumber = " + accountFrom + "");
                while (rs1.next()) {
                    double origAmt = rs1.getFloat("Amount");
                    double newAmt = origAmt - amount;
                    stmt.executeUpdate("UPDATE Accounts SET Amount = " + newAmt + " WHERE AccountNumber = " + accountFrom + ";");
                    ResultSet rs2 = stmt.executeQuery("SELECT Amount FROM Accounts WHERE AccountNumber = " + accountTo + "");
                    while (rs2.next()) {
                        double origAmt2 = rs2.getFloat("Amount");
                        double newAmt2 = origAmt2 + amount;
                        stmt.executeUpdate("UPDATE Accounts SET Amount = " + newAmt2 + " WHERE AccountNumber = " + accountTo + ";");
                        stmt.executeUpdate("INSERT INTO Transactions (AccountFrom, AccountTo, Amount, LoggedTime) VALUES (" + accountFrom + ", " + accountTo + ", " + amount + ", now());");
                        con.close();
                    }
                }
            } catch (Exception e) {
            }
        JOptionPane.showMessageDialog(null, "Transfered Successfully");
        } else {
            JOptionPane.showMessageDialog(null, "Our records indicate that you do"
                    + " not own one of the accounts specified. \n Transfer Failed");
        }
    }
}
